import random
from datetime import datetime
from flask import Blueprint, request
from flask_cors import cross_origin
from api.api_utils import catch_api_exception
from api.items import ApiResponseError, user_api_status_msg, api_status_msg
from api.datas.data_api import *
from utils import *
from blockchain import *

task_bp = Blueprint("task_api", __name__)


@task_bp.route('/add_task', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def add_task():
    request_params = request.json or request.args
    task = request_params.get('task', {})
    task['status'] = '即将众筹'
    task['task_id'] = get_uuid()
    task['create_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    task['update_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    user_id = task['user_id']
    users = get_user({'user_id': user_id})
    if not users or users[0]['is_valid'] != 1:
        raise ApiResponseError(extra_msg=user_api_status_msg.unauthorized)
    insert_task(task)
    del task['_id']
    return task


@task_bp.route('/get_my_task', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_my_task():
    request_params = request.json or request.args
    user_id = request_params.get('user_id')
    task = get_task({'user_id': user_id})
    task2 = get_touzi_task({'user_id': user_id})
    data = {
        'create_count': len(task),
        'invest_count': len(task2),
        'create_task': task,
        'invest_task': task2,

    }
    return data


@task_bp.route('/get_task_main', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_task_main():
    request_params = request.json or request.args
    # status = request_params.get('即将众筹')
    task = get_task({'status': '正在进行'})
    task_count = get_task_count()
    not_ready_count = len(task)
    other_count = task_count - not_ready_count
    data = {
        'count': {'task_count': task_count, 'other_count': other_count, 'not_ready_count': not_ready_count},
        'task': task,

    }
    return data


@task_bp.route('/get_task_list', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_task_list():
    request_params = request.json or request.args
    status = request_params.get('status', '即将众筹')
    task = get_task({'status': status})

    data = {
        'task': task
    }
    return data


@task_bp.route('/get_task_detail', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_task_detail():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    task = get_task({'task_id': task_id})
    # task = get_task({})
    if task:
        task = task[0]
    else:
        raise ApiResponseError(extra_msg=api_status_msg.error_params)
    user_id = task.get('user_id')
    users = get_user({'user_id': user_id})
    if users:
        user = users[0]
    else:
        user = {}
    data = {
        'task': task,
        'user': user

    }
    return data


@task_bp.route('/get_comment', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_comment():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    comment = get_task_comment({'task_id': task_id})
    return {'comment': comment}


@task_bp.route('/add_comment', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def add_comment():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    user_info = request_params.get('user')
    comment = request_params.get('comment')
    data = {
        'task_id': task_id,
        'user': user_info,
        'comment': comment,
        'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
    }
    add_task_comment(data)


@task_bp.route('/add_tousu', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def add_tousu():
    request_params = request.json or request.args
    task_id = request_params.get('task_id')
    task_name = request_params.get('task_name')
    user_info = request_params.get('user')
    tousu = request_params.get('tousu')
    data = {
        'tousu_id': get_uuid(),
        'task_id': task_id,
        'task_name': task_name,
        'user': user_info,
        'status': 1,
        'tousu': tousu,
        'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
    }
    add_task_tousu(data)


@task_bp.route('/get_news', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_news():
    with open('api/datas/news.txt', 'r', encoding='utf8') as f:
        data = f.readlines()
    data.reverse()
    return [i.strip() for i in data[:5]]


@task_bp.route('/get_index_tasks', methods=['GET', 'POST'])
@cross_origin()
@catch_api_exception()
def get_index_tasks():
    task = get_task(filters={'status': '正在进行'})
    if len(task) < 3:
        task2 = get_task({'status': '即将众筹'})
    else:
        task2 = []
    task.extend(task2)
    n = 4
    if n <= len(task):
        data = random.sample(task, n)
    else:
        data = task

    res = []
    for i in data:
        q = i['inputItems']
        get_price = 0
        for j in q:
            get_price += int(j.get('get_price', 0))
        i['get_price'] = get_price
        i['jindu'] = int(get_price / int(i['price']) * 100)
        res.append(i)
    return res

@task_bp.route("/task_touzi", methods=["GET", "POST"])
@cross_origin(supports_credentials=True)
@catch_api_exception()
def task_touzi():
    request_params = request.json or request.args
    money = request_params.get('money', 0)
    task_id = request_params.get('task_id')
    user_id = request_params.get('user_id')
    mobile = request_params.get('mobile')
    lcb_index = request_params.get('lcb_index', 0)
    chain_data = {'content': '投资上链:{},{},{}'.format(user_id, mobile, money),
                  'money': int(money),
                  'user_id': user_id,
                  'mobile': mobile,
                  'task_id': task_id,
                  'create_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
                  'extra': {}}
    user = get_user({'user_id': user_id})
    task = get_task({'task_id': task_id})
    if not user and not task and not mobile:
        raise ApiResponseError(extra_msg=user_api_status_msg.login_error)
    else:
        inc = user[0].get('money', 0) - int(money)
    get_price = int(task[0]['inputItems'][lcb_index].get('get_price', 0)) + int(money)
    if get_price >= int(task[0]['inputItems'][lcb_index]['price']):
        if len(task[0]['inputItems']) - 1 == lcb_index:
            update_task(task_id, {'inputItems.{}.status'.format(lcb_index): 2,
                                  'inputItems.{}.get_price'.format(lcb_index): get_price,
                                  'status': '众筹完成'})
        else:
            update_task(task_id, {'inputItems.{}.status'.format(lcb_index): 2,
                                  'inputItems.{}.get_price'.format(lcb_index): get_price})
        raise ApiResponseError(extra_msg=api_status_msg.fund_full)
    update_user(user_id, {'money': inc})

    node_list = [STATIC_NODE1, STATIC_NODE2, STATIC_NODE3, STATIC_NODE4]
    rand_node = node_list.pop(random.choice([0, 1, 2, 3]))
    block = rand_node.mine(data=chain_data)
    rand_node.sync_data(block, node_list)
    data = chain_data
    data['des'] = inc
    write_news('用户尾号{}投资上链{}元'.format(mobile[-4:], money))
    price = task[0]['inputItems'][lcb_index]['get_price'] + int(money)
    update_task(task_id, {'inputItems.{}.get_price'.format(lcb_index): price})
    update_task_money_pool(chain_data)
    del data['_id']
    return data
